package com.qf.student.exception;

import com.qf.student.response.R;
import com.qf.student.response.RCodes;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
	public R serviceExceptionHandler(BindException e) {
        BindingResult result = e.getBindingResult();
        List<ObjectError> errors = result.getAllErrors();
        List<String> errorInfo = new ArrayList<>();
        for (ObjectError error : errors) {
            errorInfo.add(error.getDefaultMessage());
        }
        return R.createFAIL(RCodes.DATA_CHECKED_ERROR.getCode(), errorInfo);
    }

}